import React from 'react';
import {
  Form,
  Input,
  Space,
  Button,
  message,
  Modal,
  TreeSelect,
  Checkbox,
  Card,
  Row,
  Col,
  Upload,
} from 'antd';
import {
  LoadingOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
  LeftOutlined,
} from '@ant-design/icons';
import { Link, connect } from 'umi';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import UploadUtil from '@/components/UploadUtil';
import request from '@/utils/request';

const { confirm } = Modal;
const apiURL = '/api/services/app/Article/';
const apiURLCate = '/api/services/app/Category/';
class ContentEdit extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      datas: {},
      cascaderOption: [],
      contentEditor: '',
      imageUrl: '',
      fileList: [],
    };
  }
  formRef: any = React.createRef();
  componentDidMount() {
    this.fetchCategory();
    if (this.props.id) {
      this.getData(this.props.id);
    }
  }
  getData = (id: number) => {
    if (id > 0) {
      request(apiURL + 'Get', {
        method: 'Get',
        params: { id },
      }).then((response) => {
        if (response && response.success) {
          let result = response.result
          result.contents = BraftEditor.createEditorState(result.contents);
          this.setState({ datas: result });
          var fileList: any = [];
          if (result.imageUrl) {
            var pics = result.imageUrl.split(',');
            pics.forEach((element: any) => {
              var obj = {
                uid: element,
                name: element,
                response: {
                  result: element,
                },
                status: 'done',
                url: UploadUtil.imgServ + element,
              };
              fileList.push(obj);
            });
          }
          this.setState({ fileList });
          this.formRef.current.setFieldsValue({ article: result });
        }
      });
    }
  };
  fetchCategory = () => {
    request(apiURLCate + 'GetTreeDataAsync', {
      method: 'Get',
      params: { layout: 'article' },
    }).then((response) => {
      const resp = response.result;
      this.setState({ cascaderOption: resp });
    });
  };
  onFinish = async (values: any) => {
    var act = 'Create';
    var method = 'Post';
    if (values.article.id > 0) {
      act = 'Update';
      method = 'Put';
    }
    values.article.contents = this.state.contentEditor;

    if (this.state.fileList) {
      var pics: string[] = [];
      this.state.fileList.forEach((element: any) => {
        pics.push(element.response.result);
      });
      values.article.imageUrl = pics.toString();
    } else {
      values.article.imageUrl = this.state.datas.ImageFileName;
    }

    request(apiURL + act, {
      method,
      data: values.article,
    }).then((response) => {
      if (response.success) {
        message.success('保存成功！');
        this.props.fetchDatas();
      } else {
        message.error('保存错误，请联系管理员');
      }
    });
  };
  ResetForm = () => {
    var data = {
      id: 0,
    };
    this.setState({ datas: data });
    this.formRef.current.resetFields();
  };
  handleDel = () => {
    request(apiURL + 'Delete', {
      method: 'Delete',
      params: { Id: this.state.datas.id },
    }).then((response) => {
      if (response.success) {
        message.success('删除成功！');
        this.props.fetchDatas();
        this.formRef.current.resetFields();
      } else {
        message.error('删除错误，请联系管理员！');
      }
    });
  };
  showConfirm = () => {
    var _this = this;
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: '删除后将不可恢复，确定删除？',
      onOk() {
        _this.handleDel();
      },
      onCancel() { },
    });
  };
  handleChange = (editorState: any) => {
    this.setState({
      contentEditor: editorState.toHTML(),
    });
  };
  handleUpload = (info: any) => {
    this.setState({ fileList: info.fileList });
  };
  render() {
    const { datas, fileList, loading } = this.state;
    const editorProps = {
      height: 120,
      onChange: this.handleChange,
    };
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div className="ant-upload-text">上传图片</div>
      </div>
    );
    const layout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
    };
    const layout2 = {
      labelCol: { span: 0 },
      wrapperCol: { span: 24 },
    };
    return (
      <>
        <Form {...layout} ref={this.formRef} onFinish={this.onFinish}>
          <Card
            title="内容编辑"
            extra={
              <Space>
                <Button type="primary" htmlType="submit" loading={loading} key="1">
                  保存
                </Button>
                <Button key="2" onClick={this.ResetForm}>
                  重设
                </Button>
                <Button
                  key="3"
                  danger
                  onClick={this.showConfirm}
                  disabled={datas.id == 0 || !datas.id}
                >
                  删除
                </Button>
              </Space>
            }
          >
            <Row gutter={16}>
              <Col span={16}>
                <Form.Item label="id" name={['article', 'id']} hidden>
                  <Input />
                </Form.Item>
                <Form.Item label="imageUrl" name={['article', 'imageUrl']} hidden>
                  <Input />
                </Form.Item>
                <Form.Item
                  name={['article', 'categoryId']}
                  label="分类"
                  rules={[{ required: true, message: '请选择分类' }]}
                >
                  <TreeSelect
                    value={this.state.value}
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    treeData={this.state.cascaderOption}
                    placeholder="请选择分类"
                    treeDefaultExpandAll
                  />
                </Form.Item>
                <Form.Item wrapperCol={{ offset: 4 }} style={{ marginBottom: 0 }}>
                  <Input.Group compact>
                    <Form.Item name={['article', 'isHot']} valuePropName="checked">
                      <Checkbox>热</Checkbox>
                    </Form.Item>
                    <Form.Item name={['article', 'isRec']} valuePropName="checked">
                      <Checkbox>推荐</Checkbox>
                    </Form.Item>
                    <Form.Item name={['article', 'isTop']} valuePropName="checked">
                      <Checkbox>置顶</Checkbox>
                    </Form.Item>
                  </Input.Group>
                </Form.Item>

                <Form.Item
                  label="标题"
                  name={['article', 'title']}
                  rules={[{ required: true, message: '请输入标题' }]}
                >
                  <Input />
                </Form.Item>
                <Form.Item label="副标题" name={['article', 'subTitle']}>
                  <Input placeholder="副标题，不超过50字符" />
                </Form.Item>
                <Form.Item name={['article', 'summary']} label="概述">
                  <Input.TextArea />
                </Form.Item>

              </Col>
              <Col span={8}>
                <Form.Item name={['article', 'tags']} label="标签">
                  <Input />
                </Form.Item>
                <Form.Item>
                  <Upload
                    action={UploadUtil.actionURL}
                    headers={{
                      Authorization: UploadUtil.accessToken,
                    }}
                    data={{
                      objectId: datas.id,
                      objectName: 'Article',
                      objectField: 'ImageUrl',
                    }}
                    listType="picture-card"
                    fileList={fileList}
                    multiple={true}
                    onChange={this.handleUpload}
                  >
                    {fileList.length >= 1 ? null : uploadButton}
                  </Upload>
                </Form.Item>

              </Col>
            </Row>
            <Form.Item {...layout2} name={['article', 'contents']}>
              <BraftEditor {...editorProps} />
            </Form.Item>
          </Card>
        </Form>
      </>
    );
  }
}
export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ContentEdit);
